package org.yray.sip.handler;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.yray.sip.base.MsgEle;
import org.yray.sip.base.SipMsg;
import org.yray.sip.rtp.sender.ISipSessionCache;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;
import org.yray.sip.utils.IcspBeanHolder;
import org.yray.sip.visit.ISipAccept;
import org.yray.sip.visit.SipVisitorFactory;


import java.util.Optional;


@Slf4j
public class ByeHandler extends MessageHandler {

    @Override
    public String[] handler(SipMsg sipMsg, SipServerContext ssc) {
        String callId=Optional.ofNullable(sipMsg.getMsgLine(MsgEle.CALL_ID)).map(String::trim).orElse(null);
        //这里分两种情况，有转人工的，有机器人的
        SipSession sipSession= IcspBeanHolder.getBean(ISipSessionCache.class).get(callId);
        if(sipSession!=null)
        {
            ISipAccept sipAccept=getSipVisitorFactory().getSipAccept(callId);
            sipAccept.accept(SipVisitorFactory.SIP_BYE_VISITOR,sipMsg,ssc);
        }
        String[] res=new String[]{doOkResp(sipMsg)};
        return res;
    }


    /***
     * Via: SIP/2.0/UDP 172.168.200.78;rport=5060;received=172.168.200.78;branch=z9hG4bKg6XFFavc1XFea
     Call-ID: 99fa3d975af84a49a8305afe4ec493d2
     From: <sip:78002@172.168.200.78>;tag=H4p78c7yH7NXj
     To: "78004" <sip:78004@172.168.200.78>;tag=81dc079b403e4d75b94a1e492faa90d8
     CSeq: 41368611 BYE
     Content-Length:  0
     * @return
     */
    private String doOkResp(SipMsg sipMsg)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("SIP/2.0 200 OK").append(MsgEle.LINE_SEPARATOR);
        String[] lines = StringUtils.split(sipMsg.toString(), MsgEle.LINE_SEPARATOR);
        for (String line : lines) {
            if (line.indexOf(MsgEle.VIA) > -1
                    || line.indexOf(MsgEle.FROM) > -1
                    || line.indexOf(MsgEle.CALL_ID) > -1
                    || line.indexOf(MsgEle.CSEQ) > -1) {
                sb.append(line).append(MsgEle.LINE_SEPARATOR);
            }
            else if(line.indexOf(MsgEle.TO) > -1)
            {
                sb.append(line.replaceFirst(":[0-9]{1,5};",";")).append(MsgEle.LINE_SEPARATOR);
            }
        }
        sb.append("Content-Length:  0").append(MsgEle.LINE_SEPARATOR);
        sb.append(MsgEle.LINE_SEPARATOR);
        return sb.toString();
    }



}
